<script setup>
import { ref, onMounted } from 'vue'
import ListHeader from '@/components/list-header.vue'
import {
  getListApi,
  changeStatusApi,
  createApi,
  deleteApi,
  changeApi,
  relevanceApi,
  deleteRelevanceApi,
  getGoodsListApi,
  addRelevanceApi
} from '@/api/category'
import { toast } from '@/utils/elnotification'
import FromDrawer from '@/components/from-drawer.vue'

//全局loading
const loading = ref(false)

//标题
const titleFromDrawer = ref('')

//绑定节点
const fromDrawerRef = ref(null)

//表单数据
const form = ref({
  name: ''
})

//表单校验规则
const rules = {
  name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }]
}

//修改的id
const changeId = ref(0)

//树形表格数据
const treeData = ref([])

//获取数据
const getList = async () => {
  const res = await getListApi()
  treeData.value = res
}

//状态切换
const onStatusChange = async (status, data) => {
  data.statusLoading = true
  try {
    await changeStatusApi(data.id, status)
    toast('修改状态成功')
    data.status = status
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    data.statusLoading = false
  }
}

//新增
const onCreate = () => {
  titleFromDrawer.value = '新增'
  form.value = {
    name: ''
  }
  fromDrawerRef.value.open()
  changeId.value = 0
}

//修改
const onEdit = (data) => {
  titleFromDrawer.value = '修改'
  const { name, id } = data
  form.value = {
    name
  }
  changeId.value = id
  fromDrawerRef.value.open()
}

//删除
const onDelete = async (id) => {
  fromDrawerRef.value.showLoading()
  try {
    await deleteApi(id)
    toast('删除成功')
    getList()
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    fromDrawerRef.value.hideLoading()
  }
}

//提交事件
const onSubmit = async () => {
  fromDrawerRef.value.showLoading()
  if (changeId.value === 0) {
    try {
      await createApi(form.value.name)
      toast('新增成功')
      getList()
    } catch (error) {
      toast('新增失败', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  } else {
    try {
      await changeApi(changeId.value, form.value.name)
      toast('修改成功')
      getList()
    } catch (error) {
      toast('修改失败', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  }
}

//关联表单节点
const fromDrawerRef2 = ref(null)

//关联表单table数据
const tableData2 = ref([])

//关联
const onRelevance = async (id) => {
  const res = await relevanceApi(id)
  tableData2.value = res
  fromDrawerRef2.value.open()
}

//删除关联
const onDeleteRelevance = async (id) => {
  loading.value = true
  try {
    await deleteRelevanceApi(id)
    toast('删除成功')
    onRelevance(tableData2.value[0].category_id)
  } catch (error) {
    toast('删除失败', 'error')
  } finally {
    loading.value = false
  }
}

const dialogVisible = ref(false)

//打开关联列表
const onSubmit2 = () => {
  dialogVisible.value = true
  getGoodsList()
}

//获取商品列表数据
const getGoodsList = async () => {
  const res = await getGoodsListApi(1)
  tableData3.value = res.list
}

//关联表单table数据
const tableData3 = ref([])

//搜索输入框
const searchVal = ref('')

//存储全选/多选的数据id
const ids = ref([])

//多选操作
const onSelectionChange = (val) => {
  ids.value = val.map((item) => item.id)
}

//关联确定
const onConfirm = async () => {
  await addRelevanceApi(tableData2.value[0].category_id, ids.value)
  await onRelevance(tableData2.value[0].category_id)
  dialogVisible.value = false
}

onMounted(() => {
  getList()
})
</script>

<template>
  <el-card shadow="never" class="border-0">
    <ListHeader @create="onCreate" @refresh="getList"></ListHeader>

    <el-tree
      :data="treeData"
      :props="{ label: 'name', children: 'child' }"
      v-loading="loading"
      node-key="id"
    >
      <template #default="{ node, data }">
        <div class="flex flex-1 justify-between items-center text-[14px]">
          <p>{{ data.name }}</p>
          <div>
            <el-button type="primary" text size="small" @click="onRelevance(data.id)"
              >推荐产品</el-button
            >
            <el-switch
              :modelValue="data.status"
              :active-value="1"
              :inactive-value="0"
              @change="onStatusChange($event, data)"
              :loading="data.statusLoading"
            />
            <el-button text type="primary" size="small" @click.stop="onEdit(data)">修改</el-button>

            <el-popconfirm
              title="是否要删除该记录？"
              confirmButtonText="确认"
              cancelButtonText="取消"
              @confirm="onDelete(data.id)"
            >
              <template #reference>
                <el-button text type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </template>
    </el-tree>
  </el-card>
  <FromDrawer destroy-on-close ref="fromDrawerRef" :title="titleFromDrawer" @submit="onSubmit">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
      </el-form-item>
    </el-form>
  </FromDrawer>

  <FromDrawer
    destroy-on-close
    ref="fromDrawerRef2"
    title="推荐产品"
    confirm-text="关联"
    @submit="onSubmit2"
  >
    <el-table :data="tableData2" border style="width: 100%">
      <el-table-column prop="goods_id" label="ID" width="90" />
      <el-table-column label="商品封面" width="150">
        <template #default="{ row }">
          <el-image style="width: 100px; height: 100px" :src="row.cover" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="180" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-popconfirm
            title="是否要删除该记录？"
            confirmButtonText="确认"
            cancelButtonText="取消"
            @confirm="onDeleteRelevance(row.id)"
          >
            <template #reference>
              <el-button text type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </FromDrawer>

  <el-dialog v-model="dialogVisible" title="商品选择" width="80%">
    <div class="border py-3 px-3">
      <div>
        <el-input
          v-model="searchVal"
          placeholder="搜索名称"
          style="width: 200px; margin-right: 20px"
        />
        <el-button type="primary" @click="toast('功能未开放', 'error')">搜索</el-button>
      </div>
      <el-table
        :data="tableData3"
        style="width: 100%"
        height="400"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="date" label="商品">
          <template #default="{ row }">
            <div class="flex items-start">
              <el-avatar shape="square" :size="50" fit="cover" :src="row.cover" />
              <div class="ml-2">
                <p>{{ row.title }}</p>
                <p class="text-rose-500">
                  ￥{{ row.min_price }} <span class="text-[#dcdfe6] mx-1">|</span>
                  <span class="text-gray-500 text-xs">￥{{ row.min_oprice }}</span>
                </p>
                <p class="text-xs mb-1 text-gray-400">
                  分类：{{ row.category ? row.category.name : '未分类' }}
                </p>
                <p class="text-xs text-gray-400">创建时间：{{ row.create_time }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="总库存" />
      </el-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onConfirm">确定</el-button>
        <el-button type="primary" @click="dialogVisible = false"> 取消 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
:deep(.el-tree-node__content) {
  padding: 20px 0;
}
</style>
